<template>
  <div class="settings-container">
    <n-card>
      <!-- 分组渲染 -->
      <template v-for="category in categories" :key="category">
        <n-h3>{{ category }}</n-h3>
        <n-list>
          <n-list-item v-for="field in getFieldsByCategory(category)" :key="field.key">
            <n-form-item :label="field.label"
            >
              <component
                :is="getComponent(field.type)"
                v-model:value="values[field.key]"
                :options="field.options"
                :placeholder="field.label"
            />

              </n-form-item>

          </n-list-item>
        </n-list>
      </template>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { useSettingsStore } from '@/stores/settingStore';

const settingsStore = useSettingsStore();
settingsStore.initializeValues(); // 初始化字段值

// 获取所有分类
const categories = computed(() => [
  ...new Set(settingsStore.fields.map((field) => field.category)),
]);

// 根据分类获取字段
const getFieldsByCategory = (category: string) => {
  return settingsStore.fields.filter((field) => field.category === category);
};

// 根据字段类型获取对应的组件
const getComponent = (type: string) => {
  switch (type) {
    case 'string':
      return 'n-input';
    case 'number':
      return 'n-input-number';
    case 'boolean':
      return 'n-switch';
    case 'select':
      return 'n-select';
    default:
      return 'n-input';
  }
};

// 双向绑定的字段值
const values = computed({
  get: () => settingsStore.values,
  set: (value) => {
    for (const key in value) {
      settingsStore.setValue(key, value[key]);
    }
  },
});
</script>

<style>
.settings-container {
  padding: 20px;
}
</style>
